package logic

import (
	"context"
	"gorm.io/gorm"
	"meituan-waimai/models/mysql"
	"net/http"

	"meituan-waimai/api/internal/svc"
	"meituan-waimai/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type NotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NotifyLogic {
	return &NotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *NotifyLogic) Notify(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	_ = req.ParseForm()
	// 获取订单号
	order_no := req.FormValue("out_trade_no")
	// 获取订单信息
	var order mysql.Order
	mysql.DB.Where("order_no = ?", order_no).First(&order)

	// 判断订单支付状态并且更新订单
	orderStatus := req.FormValue("trade_status")

	// 开始更新订单支付状态 0-未支付，1-已支付，2-支付超时或全额退款
	if orderStatus == "TRADE_SUCCESS" { // 支付完成
		// 订单支付完成，核销优惠券 更新订单状态与支付
		order.OrderStatus = "已支付，待骑手接单"
		order.OrderPayStatus = 1
		mysql.DB.Updates(&order)
		mysql.DB.Model(&mysql.Coupon{}).Where("id = ?", order.CouponId).Update("coupon_status = ?", 1)

		// 订单支付完成，开始进行骑手配送调度
		delivery := mysql.Delivery{
			Model:   gorm.Model{},
			UserId:  1,
			Rider:   1,
			OrderNo: order_no,
		}
		mysql.DB.Create(&delivery)
		order.OrderStatus = "骑手已接单，配送中"
		mysql.DB.Updates(&order)
	}
	if orderStatus == "TRADE_CLOSED" { // 支付超时或全额退款
		order.OrderPayStatus = 2
		mysql.DB.Updates(&order)
	}
	// 订单状态默认为0，不需要更改

	return
}
